package com.zed.api.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 扩展 {@link ApplicationContextAware}接口,让具有后续绑定能力
 *
 * @author Zed
 */
public interface ApplicationContextAwareExtend extends ApplicationContextAware {

    /**
     * 尝试向{@code target}绑定设置模块
     *
     * @param target             {@link T},目标对象
     * @param applicationContext {@link ApplicationContext},应用上下文
     * @return {@link boolean},返回{@code true}表示调用{@link #setApplicationContext(ApplicationContext)})}方法，否则返回{@code false}
     */
    static <T> boolean tryToBind(T target, ApplicationContext applicationContext) {
        if (target == null) return false;

        if (target instanceof ApplicationContextAware) {
            ((ApplicationContextAware) target).setApplicationContext(applicationContext);
            return true;
        }

        return false;
    }

}
